import { ref } from 'vue'
import { showLoadingToast } from 'vant'

import { IActivityAir, TableTitleType } from '../types'

import { data } from '../falsedata'

function getData(): Promise<IActivityAir[]> {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(data)
    }, 200)
  })
}

export default () => {
  const loading = ref<boolean>(false)
  const finished = ref<boolean>(false)
  const pageIndex = ref<number>(1)
  const pageSize = ref<number>(10)
  const sortId = ref<number | undefined>(undefined)
  const sortType = ref<number | undefined>(undefined)

  const tableData = ref<IActivityAir[]>([])

  async function getActiviesList() {
    const load = showLoadingToast({
      message: '加载中...',
      duration: 0,
      forbidClick: true,
    })
    try {
      const data = await getData()

      return data || []
    } catch (error: any) {
      loading.value = false
      finished.value = true
    } finally {
      load.close()
    }
  }

  async function onLoad() {
    pageIndex.value += 1

    const data = await getActiviesList()

    if (data!.length === 0) {
      finished.value = true
      return
    }

    tableData.value = [...tableData.value, ...data!]

    loading.value = false

    if (tableData.value.length >= 30 || data!.length < pageSize.value) {
      finished.value = true
    }
  }

  function handleSort(item: TableTitleType, stype: number) {
    if (item.sort === 0) return
    // tableTitle.value.forEach((v) => {
    //   v.icon = 0;
    // });

    item.icon = stype
    sortType.value = stype
    sortId.value = item.sort

    loading.value = true
    finished.value = false
    pageIndex.value = 0
    tableData.value = []

    onLoad()
  }

  pageIndex.value = 0
  loading.value = true
  onLoad()

  return {
    loading,
    finished,
    tableData,
    pageIndex,
    handleSort,
    onLoad,
  }
}
